<template>
  <div class="page-container dbu-product-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-header__content">
        <h1 class="page-title">产品管理</h1>
        <p class="page-description">管理和配置数据库产品信息</p>
      </div>
      <div class="page-header__actions">
        <el-button
          type="primary"
          :icon="Plus"
          @click="handleCreate"
        >
          新增产品
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-card__icon bg-purple">
          <el-icon><Box /></el-icon>
        </div>
        <div class="stat-card__content">
          <div class="stat-card__value">{{ productStats.totalProducts }}</div>
          <div class="stat-card__title">产品总数</div>
          <div class="stat-card__desc">系统中的数据库产品</div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-card__icon bg-green">
          <el-icon><CircleCheckFilled /></el-icon>
        </div>
        <div class="stat-card__content">
          <div class="stat-card__value">{{ productStats.activeProducts }}</div>
          <div class="stat-card__title">活跃产品</div>
          <div class="stat-card__desc">正在使用的产品</div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-card__icon bg-blue">
          <el-icon><DocumentCopy /></el-icon>
        </div>
        <div class="stat-card__content">
          <div class="stat-card__value">{{ productStats.totalSchemas }}</div>
          <div class="stat-card__title">模式总数</div>
          <div class="stat-card__desc">所有产品的数据库模式</div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-card__icon bg-orange">
          <el-icon><Files /></el-icon>
        </div>
        <div class="stat-card__content">
          <div class="stat-card__value">{{ productStats.totalTables }}</div>
          <div class="stat-card__title">表总数</div>
          <div class="stat-card__desc">所有产品中的数据表</div>
        </div>
      </div>
    </div>

    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form
        :model="searchForm"
        ref="searchFormRef"
        inline
        class="search-form__content"
      >
        <el-form-item label="产品代号">
          <el-input
            v-model="searchForm.productCode"
            placeholder="请输入产品代号"
            clearable
            class="input--medium"
          />
        </el-form-item>

        <el-form-item label="产品名称">
          <el-input
            v-model="searchForm.productName"
            placeholder="请输入产品名称"
            clearable
            class="input--medium"
          />
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.createTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :value-format="DATE_FORMATS.DATE_PICKER_VALUE"
            class="input--large"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="data-table">
      <BaseTable
        :data="products"
        :loading="loading"
        :stripe="true"
        :border="true"
        :pagination="true"
        :total="pagination.total"
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
          <el-table-column prop="productCode" label="产品代号" width="120" />
        <el-table-column prop="productName" label="产品名称" min-width="160" />
        <el-table-column prop="productDesc" label="产品描述" min-width="200" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTimeForDisplay(scope.row.createTime || '') }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
        </BaseTable>
    </div>

    <!-- 产品表单对话框 -->
    <ProductForm
      :visible="formVisible"
      :product="editingProduct"
      @close="handleFormClose"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue';
import {ElMessageBox} from 'element-plus';
import {MessageService} from '@/utils/message';
import {Box, CircleCheckFilled, DocumentCopy, Files, Plus, Refresh, Search} from '@element-plus/icons-vue';
import type {Product} from '@/types/business/product';
import productService from '@/services/productService';
import ProductForm from '@/components/business/product/ProductForm.vue';
import {DATE_FORMATS, formatDateTimeForDisplay} from '@/utils/date';
import BaseTable from '@/components/common/tables/BaseTable.vue';

// 设备宽度
const deviceWidth = ref(window.innerWidth);

// 搜索表单
const searchForm = reactive({
  productCode: '',
  productName: '',
  createTime: null as any
});

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
});

// 数据状态
const products = ref<Product[]>([]);
const loading = ref(false);
const formVisible = ref(false);
const editingProduct = ref<Product | null>(null);

// 产品统计数据
const productStats = reactive({
  totalProducts: 0,
  activeProducts: 0,
  totalSchemas: 0,
  totalTables: 0
});

// 使用统一的日期时间格式化函数

// 加载产品数据
const loadProducts = async () => {
  try {
    loading.value = true;
    const response = await productService.getProducts(
      pagination.currentPage - 1, // 转换为0-based分页
      pagination.pageSize
    );

    if (response.success) {
      products.value = response.data?.content || [];
      pagination.total = response.data?.totalElements || 0;

      // 更新统计数据
      updateProductStats(response.data?.content || []);
    } else {
      MessageService.error(response.error?.message || '加载产品数据失败');
      products.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    MessageService.error('加载产品数据失败');
    console.error('Load products error:', error);
    products.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 更新产品统计数据
const updateProductStats = (productList: Product[]) => {
  productStats.totalProducts = pagination.total;
  productStats.activeProducts = productList.length; // 目前所有产品都是启用的

  // 计算总模式数和表数（这里使用模拟数据，实际应该从API获取）
  productStats.totalSchemas = productList.reduce((sum, product) => {
    return sum + (Math.floor(Math.random() * 10) + 1); // 模拟每个产品有1-10个模式
  }, 0);

  productStats.totalTables = productList.reduce((sum, product) => {
    return sum + (Math.floor(Math.random() * 50) + 5); // 模拟每个产品有5-55个表
  }, 0);
};

// 获取全部产品统计数据
const fetchAllProductStats = async () => {
  try {
    const response = await productService.getProducts(0, 1000);
    if (response.success && response.data?.content) {
      updateProductStats(response.data.content);
    }
  } catch (error) {
    console.error('获取产品统计数据失败:', error);
  }
};

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1;
  loadProducts();
};

// 重置搜索
const handleReset = () => {
  searchForm.productCode = '';
  searchForm.productName = '';
  searchForm.createTime = null;
  pagination.currentPage = 1;
  loadProducts();
};

// 新增产品
const handleCreate = () => {
  editingProduct.value = null;
  formVisible.value = true;
};

// 编辑产品
const handleEdit = (product: Product) => {
  editingProduct.value = { ...product };
  formVisible.value = true;
};

// 删除产品
const handleDelete = async (product: Product) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除产品 "${product.productName}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    // 确保产品ID存在
    if (product.id === undefined) {
      throw new Error('产品ID不存在');
    }

    // 调用后端API删除产品
    const response = await productService.deleteProduct(product.id);

    if (response.success) {
      await loadProducts(); // 重新加载数据
    } else {
      MessageService.error(response.error?.message || '删除失败');
    }
  } catch (error: any) {
    if (error !== 'cancel' && error !== 'close') {
      MessageService.error('删除失败: ' + (error.message || ''));
      console.error('Delete product error:', error);
    }
  }
};

// 导出数据
const handleExport = () => {
  MessageService.info('导出功能开发中');
};

// 刷新数据
const handleRefresh = () => {
  loadProducts();
  MessageService.success('数据已刷新');
};

// 表单操作
const handleFormClose = () => {
  formVisible.value = false;
  editingProduct.value = null;
};

const handleFormSuccess = () => {
  formVisible.value = false;
  editingProduct.value = null;
  loadProducts();
};

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  loadProducts(); // 重新加载数据
};

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  loadProducts(); // 重新加载数据
};

// 监听窗口大小变化
const handleResize = () => {
  deviceWidth.value = window.innerWidth;
};

onMounted(async () => {
  await loadProducts();
  // 获取全局统计数据
  fetchAllProductStats();
  window.addEventListener('resize', handleResize);
});
</script>

<style scoped>
/* 产品管理页面特有样式 */

/* ===== 响应式设计 ===== */

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: stretch;
  }

  .page-header__actions {
    margin-left: 0;
    margin-top: var(--dbu-space-4);
  }

  .search-form__content {
    display: block;
  }

  .search-form__content .el-form-item {
    display: block;
    margin-bottom: var(--dbu-space-4);
  }

  .search-form__content .el-form-item__label {
    display: block;
    margin-bottom: var(--dbu-space-2);
  }
}
</style>